package fleet_management

import org.apache.commons.validator.CreditCardValidator.Mastercard;
import org.springframework.dao.DataIntegrityViolationException

class MonthlyReportController {

	static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	def index() {
		redirect(action: "list", params: params)
	}

	def list() {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[monthlyReportInstanceList: MonthlyReport.list(params), monthlyReportInstanceTotal: MonthlyReport.count()]
	}

	def create() {
		[monthlyReportInstance: new MonthlyReport(params)]
	}

	def save() {
		def monthlyReportInstance = new MonthlyReport(params)
		def monthlyReportList= new ArrayList<MonthlyReport>()

		def adminRole=session.getAttribute("adminRole")
		def vehicles=null
		if(adminRole=="Master Admin")
			vehicles=VehicleDatabase.getAll()
		else
			vehicles=VehicleDatabase.findAllByAdminRole(adminRole)

		def fuelConsumptionListObj= new ArrayList<FuelConsumption>()
		def vehicleServicingListObj= new ArrayList<VehicleServicing>()
		def maintenanceListObj= new ArrayList<Maintenance>()
		def vehicleOnDutyListObj= new ArrayList<VehicleOnDuty>()

		def fuelConsumption=null
		if(adminRole=="Master Admin")
			fuelConsumption=FuelConsumption.getAll()
		else
			fuelConsumption=FuelConsumption.findAllByAdminRole(adminRole)

		def vehicleServicing=null
		if(adminRole=="Master Admin")
			vehicleServicing=VehicleServicing.getAll()
		else
			vehicleServicing=VehicleServicing.findAllByAdminRole(adminRole)

		def maintenance=null
		if(adminRole=="Master Admin")
			maintenance=Maintenance.getAll()
		else
			maintenance= Maintenance.findAllByAdminRole(adminRole)

		def vehicleOnDuty=null
		if(adminRole=="Master Admin")
			vehicleOnDuty= VehicleOnDuty.getAll()
		else
			vehicleOnDuty=VehicleOnDuty.findAllByAdminRole(adminRole)

		if(fuelConsumption){
			for(FuelConsumption fc:fuelConsumption){
				println monthlyReportInstance.getStartdate()
				println monthlyReportInstance.getEndDate()
				if(fc.getDate()>=monthlyReportInstance.getStartdate() && fc.getDate()<=monthlyReportInstance.getEndDate()){
					fuelConsumptionListObj.add(fc)
				}
			}
		}
		if(vehicleServicing){
			for(VehicleServicing vs:vehicleServicing){
				if(vs.getServicingDate()>=monthlyReportInstance.getStartdate() && vs.getServicingDate()<=monthlyReportInstance.getEndDate()){
					vehicleServicingListObj.add(vs)
				}
			}
		}
		if(maintenance){
			for(Maintenance ma: maintenance){
				if(ma.getMaintenanceDate()>=monthlyReportInstance.getStartdate() && ma.getMaintenanceDate()<= monthlyReportInstance.getEndDate() ){
					maintenanceListObj.add(ma)
				}
			}
		}
		if(vehicleOnDuty){
			for(VehicleOnDuty vod: vehicleOnDuty){
				if(vod.getDate()>=monthlyReportInstance.getStartdate() && vod.getDate()<= monthlyReportInstance.getEndDate() ){
					vehicleOnDutyListObj.add(vod)
				}
			}
		}
		System.out.println('Test Test'+fuelConsumptionListObj.size)
		if(vehicles){
			for(VehicleDatabase v:vehicles){
				MonthlyReport monthlyReportObj= new MonthlyReport()
				monthlyReportObj.setVehicleNumber(v.getVehicleNumber())
				monthlyReportObj.setVehicleName(v.getBrandName())
				monthlyReportObj.setFuelType(v.getFuelType())
				Long fuelConsumed=0
				Long totalFuelCost=0
				Date servicingDate=null
				Long servicingCost=0
				String fuelType=""
				Date maintenanceDate=null
				String typeOfMaintenance=""
				Long maintenanceCost=0
				Long rateOfPrivateUseKm=0
				Long costOfPrivateUse=0
				Long totalKmCovered=0
				Long costPerKm
				Long averageKmPerLiter
				Long totalOperatingCost
				if(fuelConsumptionListObj){
					for(int i=0;i<fuelConsumptionListObj.size;i++){
						System.out.println("OutSide if "+fuelConsumptionListObj.get(i).getQuantityRefuled()+":"+fuelConsumptionListObj.get(i).getVehicleNumber()+":"+v.getVehicleNumber())
						if(fuelConsumptionListObj.get(i).getVehicleNumber()==v.getVehicleNumber()){
							System.out.println(fuelConsumptionListObj.get(i).getQuantityRefuled())
							fuelConsumed=fuelConsumed+fuelConsumptionListObj.get(i).getQuantityRefuled()
							totalFuelCost=totalFuelCost+fuelConsumptionListObj.get(i).getTotalCost()
						}
						System.out.println("Size of List"+fuelConsumptionListObj.size)
					}
					//				System.out.println(fuelConsumed + ":"+totalFuelCost)
					monthlyReportObj.setFuelConsumption(fuelConsumed)
					monthlyReportObj.setTotalFuelCost(totalFuelCost)
				}
				if(vehicleServicingListObj){
					for(VehicleServicing vs:vehicleServicingListObj){
						if(vs.getVehicleNumber()==v.getVehicleNumber()){
							servicingDate= vs.getServicingDate();
							servicingCost=servicingCost+vs.getTotalCost()
						}
					}
					monthlyReportObj.setServicingDate(servicingDate)
					monthlyReportObj.setServicingCost(servicingCost)
				}
				if(maintenanceListObj){
					for(Maintenance ma:maintenanceListObj){
						if(ma.getVehicleNumber()==v.getVehicleNumber()){
							maintenanceDate= ma.getMaintenanceDate()
							typeOfMaintenance=ma.getTypeOfMaintenance()
							maintenanceCost=maintenanceCost+ma.getTotalCost()
						}
					}
					monthlyReportObj.setMaintenanceDate(maintenanceDate)
					monthlyReportObj.setTypeOfMaintenance(typeOfMaintenance)
					monthlyReportObj.setMaintenanceCost(maintenanceCost)
				}
				if(vehicleOnDutyListObj){
					for(VehicleOnDuty vod:vehicleOnDutyListObj){
						if(vod.getVehicleNumber()==v.getVehicleNumber()){
							rateOfPrivateUseKm=vod.getRateOfPrivateUseKm()
							if(vod.getTotalIncomeFromPrivateUse())
								costOfPrivateUse=costOfPrivateUse+vod.getTotalIncomeFromPrivateUse()
							if(vod.getKmReadingFinish() && vod.getKmReadingInitial())
								totalKmCovered=totalKmCovered+(vod.getKmReadingFinish()-vod.getKmReadingInitial())
							totalOperatingCost=totalFuelCost+servicingCost+maintenanceCost
							if(totalKmCovered>0)
								costPerKm=totalOperatingCost/totalKmCovered
							if(fuelConsumed>0)
								averageKmPerLiter=totalKmCovered/fuelConsumed
						}
					}
					monthlyReportObj.setRateOfPrivateUseKm(rateOfPrivateUseKm)
					monthlyReportObj.setTotalIncomeFromPrivateUse(costOfPrivateUse)
					monthlyReportObj.setTotalKmCovered(totalKmCovered)
					monthlyReportObj.setCostPerKm(costPerKm)
					monthlyReportObj.setTotalOperatingCost(totalOperatingCost)
					monthlyReportObj.setAverageKmPerLiter(averageKmPerLiter)
				}
				monthlyReportList.add(monthlyReportObj)
			}
		}
		if(monthlyReportList)
			render(view: "list", model: [monthlyReportInstanceList:monthlyReportList, monthlyReportInstanceTotal: monthlyReportList.size()])
		else
			render(view: "list", model: [monthlyReportInstanceList:null, monthlyReportInstanceTotal: MonthlyReport.count()])
		//		for(MonthlyReport m :monthlyReportList){
		//			System.out.println(m.getVehicleNumber()+":"+m.getVehicleName()+":"+m.getFuelConsumption()+":"+m.getTotalFuelCost()+":"+m.getServicingDate()+":"+m.getServicingCost())
		//		}
		//		if (!monthlyReportInstance.save(flush: true)) {
		//			render(view: "create", model: [monthlyReportInstance: monthlyReportInstance])
		//			return
		//		}
		//
		//		flash.message = message(code: 'default.created.message', args: [
		//			message(code: 'monthlyReport.label', default: 'MonthlyReport'),
		//			monthlyReportInstance.id
		//		])
		//		redirect(action: "show", id: monthlyReportInstance.id)
	}

	def show() {
		def monthlyReportInstance = MonthlyReport.get(params.id)
		if (!monthlyReportInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'monthlyReport.label', default: 'MonthlyReport'),
				params.id
			])
			redirect(action: "list")
			return
		}

		[monthlyReportInstance: monthlyReportInstance]
	}

	def edit() {
		def monthlyReportInstance = MonthlyReport.get(params.id)
		if (!monthlyReportInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'monthlyReport.label', default: 'MonthlyReport'),
				params.id
			])
			redirect(action: "list")
			return
		}

		[monthlyReportInstance: monthlyReportInstance]
	}

	def update() {
		def monthlyReportInstance = MonthlyReport.get(params.id)
		if (!monthlyReportInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'monthlyReport.label', default: 'MonthlyReport'),
				params.id
			])
			redirect(action: "list")
			return
		}

		if (params.version) {
			def version = params.version.toLong()
			if (monthlyReportInstance.version > version) {
				monthlyReportInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
						[
							message(code: 'monthlyReport.label', default: 'MonthlyReport')]
						as Object[],
						"Another user has updated this MonthlyReport while you were editing")
				render(view: "edit", model: [monthlyReportInstance: monthlyReportInstance])
				return
			}
		}

		monthlyReportInstance.properties = params

		if (!monthlyReportInstance.save(flush: true)) {
			render(view: "edit", model: [monthlyReportInstance: monthlyReportInstance])
			return
		}

		flash.message = message(code: 'default.updated.message', args: [
			message(code: 'monthlyReport.label', default: 'MonthlyReport'),
			monthlyReportInstance.id
		])
		redirect(action: "show", id: monthlyReportInstance.id)
	}

	def delete() {
		def monthlyReportInstance = MonthlyReport.get(params.id)
		if (!monthlyReportInstance) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'monthlyReport.label', default: 'MonthlyReport'),
				params.id
			])
			redirect(action: "list")
			return
		}

		try {
			monthlyReportInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [
				message(code: 'monthlyReport.label', default: 'MonthlyReport'),
				params.id
			])
			redirect(action: "list")
		}
		catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [
				message(code: 'monthlyReport.label', default: 'MonthlyReport'),
				params.id
			])
			redirect(action: "show", id: params.id)
		}
	}
}
